﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Security.Cryptography;
using GestorDeFlotasDesktop;
	
		 
	
namespace GestorDeFlotasDesktop.Login
{
    public partial class Login : Form {
   
        public Base cBase;
    
        int intentos = 1;

        public Login ()
        {
            InitializeComponent();  
        }

        public Login(Base mibase)
        {
            cBase = mibase;
            InitializeComponent();
        }
        
        private void Login_Load(object sender, EventArgs e)
        {
            textLogin.Clear();
            textPassword.Clear();
        }

        private bool verificarCampos()
        {
            if (this.textLogin.Text != string.Empty && this.textPassword.Text != string.Empty)
                return true;
            else
            {
                MessageBox.Show("Debe completar los campos Usuario y Password.", "Datos incompletos", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
        }

        private void btnLoginOK_Click(object sender, EventArgs e)
        {
             //hago SHA256 de el usuario y de la clave.///
            String user =this.SHA256Encrypt(textLogin.Text);
            String pass = this.SHA256Encrypt(textPassword.Text);
            if (this.verificarCampos()&& intentos < 3)
            {

                try
                {
                    // Consulta SQL -- puede pasarce a un sp_ para encapsularlo

/*
                        string Consulta =
                            "select distinct F.Nombre " +
                            "from ULTIMO_COMMIT.Usuario U inner join ULTIMO_COMMIT.Usuario_Rol UR on U.ID_Usuario = UR.ID_Usuario " +
                            "inner join ULTIMO_COMMIT.Rol R on UR.ID_Rol = R.ID_Rol " +
                            "inner join ULTIMO_COMMIT.Rol_Funcionalidad RF on R.ID_Rol = RF.ID_Rol " +
                            "inner join ULTIMO_COMMIT.Funcionalidad F on RF.ID_Funcionalidad = F.ID_Funcionalidad " +
                            "where R.Habilitado =1 " +
                            "AND U.Usuario = '" + user + "'" +
                            "AND U.Password = '" + pass + "'";
                    
                    cBase.conBase.Open();
                    System.Data.SqlClient.SqlCommand OrdenBase = new System.Data.SqlClient.SqlCommand(Consulta, cBase.conBase);
                    System.Data.SqlClient.SqlDataReader result = OrdenBase.ExecuteReader();
*/

                    cBase.conBase.Open();
                    System.Data.SqlClient.SqlCommand OrdenBase = new System.Data.SqlClient.SqlCommand("ULTIMO_COMMIT.sp_verificacion_Usuario", cBase.conBase);
                    OrdenBase.CommandType = CommandType.StoredProcedure;
                    OrdenBase.Parameters.Add("@usuario",user);
                    OrdenBase.Parameters.Add("@password", pass);
                    System.Data.SqlClient.SqlDataReader result = OrdenBase.ExecuteReader();
                    if (result.HasRows)
                    {
                        String[] Funcionalidades = new String[15];
                        int i = 0;
                        while (result.Read())
                        {
                            // Cargo las funcionalidades
                            Funcionalidades[i] = (String)result.GetValue(0);
                            i++;
                        }
                        new GestorDeFlotasDesktop.Menu(cBase, this, Funcionalidades).Show();
                        this.Visible = false;
                    }
                  cBase.conBase.Close();

                }
                catch (Exception j)
                {
                    MessageBox.Show(j.Message);
                    if (j.Message == "Error Password")
                         intentos++;
                    cBase.conBase.Close();
                }

            }
            else if(intentos == 3)
            {
                //bloquear usuario por cantidad de errores.
                string Consulta = "update ULTIMO_COMMIT.Usuario set Habilitado = 0 where Usuario='"+user+"'" ;
                cBase.conBase.Open();
                System.Data.SqlClient.SqlCommand OrdenBase = new System.Data.SqlClient.SqlCommand(Consulta, cBase.conBase);
                OrdenBase.ExecuteNonQuery();
                cBase.conBase.Close();


                MessageBox.Show("El Usuario:" + textLogin.Text+ " ha sido bloqueado, comuniquese con el administrador");
                this.textLogin.Clear();
                this.textPassword.Clear();
                intentos = 1;
            }
            
        }


        // estraido de la internet///
        public string SHA256Encrypt(string input)
        {
            SHA256 provider = new SHA256Managed();

            byte[] inputBytes = Encoding.UTF8.GetBytes(input);
            byte[] hashedBytes = provider.ComputeHash(inputBytes);

            StringBuilder output = new StringBuilder();

            for (int i = 0; i < hashedBytes.Length; i++)
                output.Append(hashedBytes[i].ToString("x2").ToLower());

            return output.ToString();
        }  



        private void btnLoginCancelar_Click(object sender, EventArgs e)
        {
            base.Close();
            Application.Exit();
        }

        private void textLogin_TextChanged(object sender, EventArgs e)
        {
            intentos = 1;
        }


    }
}
